package com.blockchain.console.service.system.achieve;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.AbstractConsoleService;
import com.blockchain.framework.data.sql.SQLConnectionProvider;
import com.blockchain.framework.resource.ResourceNotFoundException;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.query.ItemParser;

public abstract class AbstractSystemService extends AbstractConsoleService {

	public AbstractSystemService(ServiceResource serviceResource) {
		super(serviceResource);
	}

	protected Connection getConnection() throws ResourceNotFoundException,
			SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER)
				.getConnection(ConsoleConst.DB_CONSOLE);
	}

	protected Connection getConnection(String db)
			throws ResourceNotFoundException, SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER)
				.getConnection(db);
	}
	
	protected SQLConnectionProvider getSQLConnectionProvider()
			throws ResourceNotFoundException, SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER);
	}
	
	protected String selectString(String db, String sql,
			Object... paramters) throws SQLException {
		final String decimal = "";
		return select(getConnection(db), new ItemParser<String>() {
			@Override
			public String parse(ResultSet resultSet) throws SQLException {
				if (resultSet.next()) {
					return resultSet.getString(1);
				}
				return decimal;
			}
		}, sql, paramters);
	}
}
